package com.example.order.controller;

import com.example.order.api.OrderApi;
import com.example.order.client.AccountClient;
import com.example.order.client.StorageClient;
import com.example.order.servive.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class OrderController implements OrderApi {

    @Autowired
    private OrderService orderService;

    @Autowired
    private StorageClient storageClient;

    @Autowired
    private AccountClient accountClient;

    @Override
    public Boolean create(String userId, String commodityCode, int orderCount) {
        int totalMoney = orderService.calculateMoney(commodityCode, orderCount);
        Boolean orderSuccess = orderService.create(userId, commodityCode, orderCount);
        if(!orderSuccess){
            throw new RuntimeException("订单创建失败");
        }
        log.info("订单创建成功");
        Boolean accountSuccess = accountClient.debit(userId, totalMoney);
        if(!accountSuccess){
            throw new RuntimeException("账户扣钱失败！");
        }
        log.info("扣钱成功");
        return true;
    }

    @GlobalTransactional(name = "my_test_tx_group",rollbackFor = Exception.class)
    @Override
    public Boolean testDisTransaction(String userId, String commodityCode, int orderCount) {
        Boolean orderSuccess = create(userId, commodityCode, orderCount);
        Boolean storageSuccess = storageClient.deduct(commodityCode, orderCount);
        if(!storageSuccess) {
            throw new RuntimeException("库存不足");
        }
        return true;
    }
}
